#include "Server.h"

#include <memory>

#include "KVCommand.h"
#include "KVMiddleware.h"

Server::Server(boost::asio::io_context &ioContext, int port)
    : acceptor_(ioContext, tcp::endpoint(tcp::v4(), port)) {
    auto kv_command_middleware = std::make_shared<KVCommand>();
    kv_middleware_ = std::make_shared<KVMiddleware>(kv_command_middleware);
    boost::asio::co_spawn(ioContext, accept(), boost::asio::detached);
}

boost::asio::awaitable<void> Server::accept() {
    while (true) {
        tcp::socket socket = co_await acceptor_.async_accept(boost::asio::use_awaitable);
        std::make_shared<Session>(std::move(socket), kv_middleware_)->start();
    }
}